<?php


namespace app\services;


use think\Exception;
use think\facade\Cache;

class Cart
{
    static private $_instance = null;
    private $redis = null;

    private final function __construct()
    {
        $this->redis = Cache::store('redis');
    }


    static public function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new Cart();
        }
        return self::$_instance;
    }


    /**
     * 加入购物车
     * @param $userId
     * @param $goods
     * @param $goodsNum
     * @return int[]
     */
    public function addCart($userId, $goods, $goodsNum)
    {

        $hashKey = 'userCart:' . $userId;
        if (!$this->redis->exists($hashKey)) {
            if ($goodsNum <= 0) {
                return ['code' => 0];
            }
            $this->redis->hset($hashKey, $goods->goods_spec_id, $goodsNum);
        } else {
            $originNum = $this->redis->hget($hashKey, $goods->goods_spec_id);
            if ($originNum + $goodsNum < 0) {
                return ['code' => 0];
            } elseif ($originNum + $goodsNum < 1) {
                $this->cartDelOne($userId, $goods->goods_spec_id);
            } else {
                $this->redis->hincrby($hashKey, $goods->goods_spec_id, $goodsNum);
            }
        }
        return ['code' => 1];
    }


    /**
     * 单删
     * @param $userId
     * @param $goodsId
     * @return mixed
     */
    public function cartDelOne($userId, $goodsId)
    {
        $hashKey = 'userCart:' . $userId;
        if(!is_array($goodsId)){
            $goodsId = explode(',',$goodsId);
        }
        foreach ($goodsId as $v){
            $this->redis->hDel($hashKey, $v);
        }
        return true;
    }


    /**
     * 购物车列表
     * @param
     * @return void
     */
    public function cartList($userId)
    {

        $hashKey = "userCart:" . $userId;
        return $this->redis->hGetAll($hashKey);

    }


    /**
     * 清空购物车
     * @param $userId
     * @return mixed
     */
    public function cartDelAll($userId)
    {
        $hashKey = "userCart:" . $userId;
        return $this->redis->del($hashKey);
    }



    public function cartNum($userId,$goodsId){
        $hashKey = "userCart:" . $userId;
        return $this->redis->hget($hashKey,$goodsId);
    }

}